<?php

namespace app\controller;

use app\BaseController;
use app\common\Snowflake;
use GuzzleHttp\Client;
use think\facade\Db;
use think\Request;
use think\response\Json;
use GuzzleHttp\Exception\GuzzleException;

class User extends BaseController
{

    //用户列表
    public function userList(Request $request): Json
    {
        try {
            $param = $request->param();

            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            $map = [];

            if ($param['id'] ?? "") {
                $map[] = ['mu.id', '=', $param['id']];
            }
            //用户账号
            if ($param['mobile_phone'] ?? "") {
                $map[] = ['mu.mobile_phone', '=', $param['mobile_phone']];
            }
            //todo 会员状态搜索

            //账号状态
            if ($param['is_banned'] ?? "") {
                $map[] = ['aus.is_banned', '=', $param['is_banned']];
            }

            // 关联查询会员信息、用户状态和手机号验证信息
            $dataObj = Db::name('member_user')->alias('mu')
                ->leftJoin('vip_user vu', 'mu.id = vu.user_id')
                ->leftJoin('member_user_authentication mua', 'mu.id = mua.id')
                ->leftJoin('auth_user_status aus', 'mu.id = aus.user_id')
                ->leftJoin('auth_login_log all', 'mu.id = all.user_id')
                ->field("mu.id,mu.mobile_phone,vu.type,vu.status,vu.expired_at,mu.wechat_id,mua.name,mu.avatar,aus.is_banned,all.created_at as last_login_time,member_user.created_at,last_login_time")
                ->where($map)
                ->order('mu.created_at', 'desc')
                ->page($page, $limit)
                ->select();
            $dataArr = $dataObj->toArray();

            $count = Db::name('member_user')->alias('mu')
                ->leftJoin('vip_user vu', 'mu.id = vu.user_id')
                ->leftJoin('member_user_authentication mua', 'mu.id = mua.id')
                ->leftJoin('auth_user_status aus', 'mu.id = aus.user_id')
                ->leftJoin('auth_login_log all', 'mu.id = all.user_id')
                ->fetchSql(false)
                ->where($map)
                ->count();

            // 处理数据，防止前端数据精度丢失
            foreach ($dataArr as $key => $value) {

                if (!empty($value['avatar']) && !str_contains($value['avatar'], 'https://')) {
                    $cdn = config('basic.cdn');
                    $dataArr[$key]['avatar'] = $cdn . $value['avatar'];
                } else {
                    $dataArr[$key]['avatar'] = "";
                }

                $dataArr[$key]['id'] = strval($value['id']);
                if ($value['type'] == "" && $value['status'] == "" && $value['expired_at'] == "") {
                    $dataArr[$key]['user_type'] = "普通用户"; //未开通
                } elseif ($value['type'] == "TIME_LIMITED" && $value['status'] == "EXPIRED") {
                    $dataArr[$key]['user_type'] = "普通用户"; //开通后-已过期
                } elseif ($value['type'] == "TIME_LIMITED" && $value['status'] == "ACTIVATED") {
                    $dataArr[$key]['user_type'] = "时效会员";
                } elseif ($value['type'] == "PERPETUAL" && $value['status'] == "ACTIVATED") {
                    $dataArr[$key]['user_type'] = "永久用户";
                } else {
                    $dataArr[$key]['user_type'] = "此用户会员状态错误";
                }


            }

            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '获取用户列表失败：' . $e->getMessage()]);
        }
    }

    //获取用户id, 根据用户id去查library, 再根据library去查product, 关联查询
    public function userGameLibrary(Request $request): Json
    {
        try {
            $param = $request->param();

            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            $map = [];
            //游戏名称搜索
            if ($param['name'] ?? "") {
                $map[] = ['gp.name', 'like', '%' . $param['name'] . '%'];
            }
            //Appid搜索
            if ($param['app_id'] ?? "") {
                $map[] = ['gp.app_id', 'like', '%' . $param['app_id'] . '%'];
            }

            if ($param['user_id'] ?? "") {
                $map[] = ['gl.user_id', '=', $param['user_id']];
            }

            // 关联查询用户游戏库和产品信息
            $dataObj = Db::name('game_library')->alias('gl')
                ->leftJoin('game_product gp', 'gl.product_id = gp.id')
                ->field("gl.id,gl.user_id,gl.product_id,gl.sku_id,gp.name,gp.app_id")
                ->where($map)
                ->order('gl.created_at', 'desc')
                ->page($page, $limit)
                ->select();
            $dataArr = $dataObj->toArray();
            foreach ($dataArr as $key => $value) {
                //id strval 避免精度丢失
                $dataArr[$key]['id'] = strval($value['id']);

            }


            $count = Db::name('game_library')->alias('gl')
                ->leftJoin('game_product gp', 'gl.product_id = gp.id')
                ->fetchSql(false)
                ->where($map)
                ->count();
            return  json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);
        } catch (\Exception $e) {

            return json(['code' => -1, 'msg' => '获取用户游戏库失败：' . $e->getMessage()]);
        }
    }

    //根据id删除用户的已购游戏
    public function deleteUserGameLibrary(Request $request): Json
    {
        try {
            $param = $request->param();

            $id = $param['id'] ?? "";

            if (empty($id)) {
                return json(['code' => -1, 'msg' => 'ID不能为空']);
            }

            // 删除用户游戏库
            Db::name('game_library')->where('id', $id)->delete();

            return json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    //修改用户->可修改用户的状态, 等级
    public function updateUser(Request $request): Json
    {
        try {
            //开启事务
            Db::startTrans();
            $param = $request->param();


            $userId = $param['user_id'] ?? "";
            $is_banned = $param['is_banned'] ?? "";     //用户状态 -> 是否被禁用
            $user_type = $param['user_type'] ?? "";     //用户类型  1 2 3 4
            $expired_at = $param['expired_at'] ?? "";   //会员到期时间
            $avatar = $param['avatar'] ?? "";

            if (empty($userId)) {
                return json(['code' => -1, 'msg' => '用户ID不能为空']);
            }

            // 修改用户的头像
             if (!empty($avatar)) Db::name('member_user')->where('user_id', $userId)->update(['avatar' => $avatar]);

            // 更新用户是否被禁用 修改这两个字段 auth_user_status
            Db::name('auth_user_status')->where('user_id', $userId)->update(['is_banned' => $is_banned]);

            //根据用户类型去更新用户的会员状态
            if ($user_type == 1) {
                //普通用户 -> 删除vip信息
                Db::name('vip_user')->where('user_id', $userId)->delete();
            } elseif ($user_type == 2) {
                //时效用户 -> 时效会员已过期
                Db::name('vip_user')->where('user_id', $userId)->update(['type' => 'TIME_LIMITED', 'status' => 'EXPIRED', 'expired_at' =>  ""]);
            } elseif ($user_type == 3) {
                //时效会员
                Db::name('vip_user')->where('user_id', $userId)->update(['type' => 'TIME_LIMITED', 'status' => 'ACTIVATED', 'expired_at' => $expired_at]);
            } elseif ($user_type == 4) {
                //永久会员
                Db::name('vip_user')->where('user_id', $userId)->update(['type' => 'PERPETUAL', 'status' => 'ACTIVATED', 'expired_at' =>  null]);
            }
            // 提交事务
            Db::commit();
            return json(['code' => 0, 'msg' => '修改成功']);

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => -1, 'msg' => '修改失败：' . $e->getMessage()]);
        }
    }


}